package com.hibernate.hrm.controller.department;

import com.hibernate.hrm.entity.Department;
import com.hibernate.hrm.entity.User;
import com.hibernate.hrm.dao.DepartmentRepository;
import com.hibernate.hrm.service.login.OperateLogService;
import com.hibernate.hrm.util.ExcelExportUtil;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.security.core.annotation.AuthenticationPrincipal;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.IOException;
import java.util.List;

@RestController
@RequestMapping("/api/department")
public class DepartmentExportController {

    private final DepartmentRepository departmentRepository;
    private final OperateLogService operateLogService;

    public DepartmentExportController(DepartmentRepository departmentRepository,
                                      OperateLogService operateLogService) {
        this.departmentRepository = departmentRepository;
        this.operateLogService = operateLogService;
    }

    @GetMapping("/export")
    public void exportDepartmentsToExcel(HttpServletResponse response,
                                         @AuthenticationPrincipal User currentUser,
                                         HttpServletRequest request) throws IOException {
        List<Department> departments = departmentRepository.findAll();
        ExcelExportUtil.exportDepartmentsToExcel(departments, response);
        // 记录导出日志
        operateLogService.recordExportLog(currentUser, departments.size(), request);
    }
}